package rbac.service.array;

import rbac.domain.dto.BaseDto;
import rbac.domain.dto.DeptDto;
import rbac.domain.entity.BaseEntity;
import rbac.domain.entity.Dept;
import rbac.domain.vo.BaseVo;
import rbac.domain.vo.DeptVo;
import rbac.domain.vo.Result;
import rbac.service.IBaseService;

import java.util.Arrays;

/**
 * 基于数值存储的业务层基类
 */

abstract class BaseService <Entity extends BaseEntity,
        Dto extends BaseDto,
        Vo extends BaseVo> implements IBaseService<Entity, Dto> {

    static final int DATA_SIZE = 100; // 实体对象存储量设为最多100个

    Entity[] data; // 实体对象存储数组

    int idCounter = 1;

    Vo[] temp;

    @Override
    public boolean existsById(int id){
        return id >= 1 && id < idCounter && data[id] != null;
    }

    @Override
    public Entity findById(int id) {
        if (existsById(id)) {
            return data[id];
        }
        return null;
    }

    abstract Vo convertToVo(Entity entity);

    @Override
    public Result list(){
        int length = 0; // ⽤于记录临时数组的实际存储⻓度

        for (int i = 1; i < idCounter; i++){
            if (data[i] != null){
                temp[length++] = convertToVo(data[i]);
            }
        }
        return Result.success(" 查询成功", Arrays.copyOf(temp, length)); // 返回临时数组的有效部分
    }

    abstract Entity createEntity(Dto dto, int id);

    @Override
    public Result create(Dto dto){ // 用dto数据传输对象来传入参数
        if (idCounter > DATA_SIZE){
            return Result.failure("创建失败，超出存储容量");
        }

        Entity entity = createEntity(dto, idCounter++);

        data[entity.getId()] = entity; // 将新部⻔对象存储到数据数组中

        return Result.success(" 创建成功", null);
    }

    abstract void updateEntity(Dto dto, Entity entity);

    @Override
    public Result update(Dto dto, int id){
        if (!existsById(id)){
            return Result.failure("更新失败，不存在该数据");
        }

        Entity entity = data[id]; // 获取指定ID 的部⻔对象

        updateEntity(dto, entity);

        return Result.success(" 更新成功", null);
    }


}

